<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\models\Department;
use yii\data\Pagination;
use app\models\User;
use app\models\Institution;
use app\models\Integral;
use app\models\Manager;
use Yii;

class UserController extends BaseController
{
    public static $pageSize = 10;
    public static $uploadDir = '../web/uploads';
    public static $demo_file = 'exportUserdemo.xlsx';
    public static $download = 'download';

    /**
     * 用户列表主页
     * @return string
     */
    public function actionIndex()
    {
        //当前用户的机构-----------------------------------------------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        $department = $current_console_user['department']['id'];
        //---------------------------------------------------------------

        $request = \Yii::$app->request;

        //下拉选择的机构
        $institutionCode = $institution;
        if ($institutionCode == '0') {
            $institutionCode = $request->get("institutionCode", '');
        }

        //下拉列表相关数据
        $selectList = Institution::getInstitutionSelectList($institution, $institutionCode);

        $department_id = $request->get("department_id");
        if ($department_id == '') {
            $department_id = $department;
        }

        $start = $request->get("page");

        $status = $request->get("status");
        $filter = $request->get("filter");

        if ($start == '') {
            $start = '0';
        } else {
            $start = ($start - 1) * self::$pageSize;
        }
        if ($status == '') {
            $status = '1';
        }
        if ($filter == '') {
            $filter = '0';
        }

        //判断是否部门管理员，部门管理员只显示自己部门和下属部门
        /*        $isDepartmentAdmin = Department::isDepartmentManager($current_console_user['id']);
                $department_id = $request->get('department_id');
                $code_tree = '';
                if ($isDepartmentAdmin) {
                    $department = Department::getDepartmentByManagerId($current_console_user['id']);
                    $code_tree = $department['code_tree'];
                }*/

        $total = User::getUserListTotal($status, $filter, $institutionCode, $department_id);
        $total_page = $total['totalnum'];
        $record = User::getUserList($start, self::$pageSize, $status, $filter, $institutionCode, $department_id);

        $pagination = new Pagination([
            'defaultPageSize' => self::$pageSize,
            'totalCount' => $total_page,
        ]);

        //部门下拉列表
        /*        $departments = null;
                if ($isDepartmentAdmin) {
                    $de = Department::getDepartmentByManagerId($current_console_user['id']);
                    $departments = Department::getListTree2($institutionCode, $de['id']);
                }*/


        return $this->render('index',
            [
                'institution' => $institution,
                'selectedInstitution' => $selectList['selectedInstitution'],
                'institutionList' => $selectList['institutionList'],
                'pagination' => $pagination,
                'record' => $record,
                'status' => $status,
                'filter' => $filter,
                'total' => $total,
                // 'isDepartmentAdmin' => $isDepartmentAdmin,
                'department' => $department,
                'selectedDepartment' => $department_id
            ]);
    }

    /**
     * 用户详情
     * @return string
     */
    public function actionUserDetailHandler()
    {
        $request = \Yii::$app->request;
        $userId = $request->post("id");

        $record = User::getUser($userId);

        return $this->renderJson(['record' => $record], 0, 0);
    }

    /**
     * 用户详情
     * @return string
     */
    public function actionUserDetailPartview()
    {
        $request = \Yii::$app->request;
        $userId = $request->post("id");
        $record = User::getUser($userId);
        return $this->renderPartial('user-detail-partview', ['record' => json_encode($record)]);
    }

    /**
     * 确认添加修改用户
     * @return string
     */
    public function actionAddUserHandler()
    {
        $current_console_user = Manager::getCurrentManager();
        $department = $current_console_user['department']['id'];

        $request = \Yii::$app->request;
        $record = [];
        $record['id'] = $request->post("id");
        $record['code'] = 0;
        $record['name'] = $request->post("name");
        $record['institution_code'] = $request->post("institution_code");
        $record['phone'] = $request->post("phone");
        $record['remark'] = $request->post("remark");
        $record['isEnabled'] = $request->post("isEnabled");
        $record['wx_openid'] = $request->post("wx_openid");
        $record['header_url'] = $request->post("header_url");
        $record['department_id'] = $request->post("department");
        $record['is_del_department'] = '1';
        $record['del_department'] = $department;

        $result = User::addUser($record);

        return $this->renderJson(0, $result['result'], 0);
    }


    /**
     * 变更用户状态
     * @return string
     */
    public function actionModifyStatusHandler()
    {
        $request = \Yii::$app->request;
        $id = $request->post("id");
        $isEnabled = $request->post("isEnabled");
        $result = User::setUserStatus($id, $isEnabled);
        return $this->renderJson(0, 0, $result);
    }

    /**
     * 导入用户
     * @return string
     * @throws \Exception
     * @throws \PHPExcel_Exception
     * @throws \yii\db\Exception
     */
    public function actionImportUser()
    {
        //当前操作人员id----------------
        $current_console_user = Manager::getCurrentManager();
        $operator_id = $current_console_user['id'];
        //------------------------------

        $request = \Yii::$app->request;

        //下拉选择的机构
        $institutionId = $request->get("institutionCode");
        $importTyp = $request->get("importType");
        $departmentId = $request->get("departmentId");

        $flag = 0;
        $msg = "";
        $reason = "管理员调整积分";
        $walfare_type = 0;

        $iCount = 0;

        $right_data = array();
        $error_data = array();

        $file = $_FILES['file']['name'];
        if ($_POST) {
            if (empty($file)) {
                $flag = 2;
                $msg = json_encode("请选择要上传的文件");
            } else {
                $file_info = pathinfo($file);
                $file_ext = $file_info['extension'];

                if (!in_array($file_ext, array('xls', 'xlsx'))) {
                    $flag = 2;
                    $msg = json_encode("文件类型不正确，仅支持xls,xlsx类型的文件！");
                } else {
                    $objPHPExcel = \PHPExcel_IOFactory::load($_FILES['file']['tmp_name']);

                    $sheet = $objPHPExcel->getSheet(0);
                    $highestRow = $sheet->getHighestRow();           //取得总行数
                    $highestColumn = $sheet->getHighestColumn(); //取得总列

                    if ($highestRow > 5002) {
                        $flag = 2;
                        $msg = json_encode("一次导入数据不能超过5000条记录！");
                    } else {
                        //检查文件正确性
                        for ($j = 2; $j <= $highestRow; $j++)                        //从第二行开始读取数据
                        {
                            $is_error = 0;
                            $v = array();

                            for ($k = 'A'; $k <= $highestColumn; $k++)            //从A列读取数据
                            {
                                $value = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();//读取单元格
                                $v['error'] = "";

                                if ($importTyp == '1') {
                                    //获取数据
                                    switch ($k) {
                                        case 'A':
                                            $v['usercode'] = trim($value);
                                            break;
                                        case 'B':
                                            $v['phone'] = trim($value);
                                            break;
                                        case 'C':
                                            $v['name'] = trim($value);
                                            break;
                                        case 'D':
                                            $v['integral'] = trim($value);
                                            break;
                                        case 'E':
                                            $v['type'] = trim($value);
                                            break;
                                    }
                                } else {
                                    //获取数据
                                    switch ($k) {
                                        case 'A':
                                            $v['phone'] = trim($value);
                                            break;
                                        case 'B':
                                            $v['name'] = trim($value);
                                            break;
                                    }
                                }
                            }

                            if ($importTyp == '1') {
                                if ($v['usercode'] == "") {
                                    $v['error'] .= '用户编码号码不允许为空！';
                                    $is_error = 1;
                                    $flag = 1;

                                }
                                if (!($v['integral'] != "" && is_numeric($v['integral']))) {
                                    $v['error'] .= '积分不允许为空，或不为数字！';
                                    $is_error = 1;
                                    $flag = 1;
                                }
                                if (!($v['type'] == "add" || $v['type'] == "edit")) {
                                    $v['error'] .= '类型不是add或edit！';
                                    $is_error = 1;
                                    $flag = 1;
                                }
                                //导入修改会员高级权限 ，根据用户编码来新增和修改用户数据
                                $v['id'] = $v['usercode'];
                                $v['code'] = $v['usercode'];
                                $v['integral'] = (int)$v['integral'];

                            } else {
                                //导入会员
                                $v['id'] = 0;
                                $v['code'] = 0;

                                if ($v['phone'] == "") {
                                    $v['error'] .= '手机号码不允许为空！';
                                    $is_error = 1;
                                    $flag = 1;

                                }
                            }


                            $v['institution_code'] = $institutionId;
                            $v['remark'] = '';
                            $v['isEnabled'] = 1;

                            //正确的数据 装入到正确记录数组
                            //错误的数据 装入到错误记录数组
                            if ($is_error) {
                                $error_data[] = $v;
                            } else {
                                $right_data[] = $v;
                                $iCount++;
                            }
                        }
                        $msg = json_encode($error_data);

                    }
                }
            }
        }

        if ($flag == 0) {
            //确认添加用户或导入积分
            $transaction = \Yii::$app->db->beginTransaction();
            try {

                //导入修改会员高级权限
                if ($importTyp == '1') {
                    $send_record_id = Integral::saveInstitutionWalfare($institutionId, $operator_id, $reason, $walfare_type);
                    if ($send_record_id == '0') {
                        throw new \Exception('写入机构福利失败！');
                        $msg = json_encode('写入机构福利失败！');
                    }
                }
                foreach ($right_data as $k => $record) {
                    $record['department_id'] = $departmentId;
                    if ($importTyp == '1') {
                        $record['send_record_id'] = $send_record_id;
                        $record['reason'] = $reason;
                        $result = User::setUserIntegral($record);

                    } else {
                        //导入会员
                        $record['wx_openid'] = '';
                        $record['header_url'] = '';
                        $result = User::addUser($record);
                    }
                    if ($result['result']) {
                        if ($result['result'] == '1') {
                            $flag = 2;
                            $msg = json_encode('操作用户失败，用户[' . $record['name'] . ']编码' . $record['code'] . '重复！请检查导入文件中无重复编码，系统中无此编码的用户！');
                            throw new \Exception('操作用户失败，用户[' . $record['name'] . ']编码' . $record['code'] . '重复！请检查导入文件中无重复编码，系统中无此编码的用户！');
                        } else if ($result['result'] == '2' || $result['result'] == '9') {
                            $flag = 2;
                            $msg = json_encode('操作用户失败，用户[' . $record['name'] . ']电话号码' . $record['phone'] . '重复！请检查导入文件中无重复电话号码，系统中无此电话号码的用户！');
                            throw new \Exception('操作用户失败，用户[' . $record['name'] . ']电话号码' . $record['phone'] . '重复！请检查导入文件中无重复电话号码，系统中无此电话号码的用户！');
                        } else {
                            $flag = 2;
                            $msg = json_encode('操作用户失败，用户[' . $record['name'] . ']发生未知异常！');
                            throw new \Exception('操作用户失败，用户[' . $record['name'] . ']发生未知异常！');
                        }
                    }
                }

                $transaction->commit();
            } catch (\Exception $e) {
                $transaction->rollBack();
                //throw $e;
            }
        }
        return $this->renderJson(['iCount' => $iCount, 'ins' => $institutionId], $flag, $msg);
    }

    /**
     * 导出会员积分
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function actionExportUserListHandler()
    {
        $request = \Yii::$app->request;

        //下拉选择的机构
        $institutionId = $request->post("institutionCode");
        $status = $request->post("status");
        $filter = $request->post("filter");
        $department_id = $request->post("department_id");
        $insUserList = User::getUserList(0, 0, $status, $filter, $institutionId, $department_id);
        $objPHPExcel = \PHPExcel_IOFactory::load(self::$demo_file);
        // 给表格添加数据

        //得到当前活动的表,注意下文教程中会经常用到$objActSheet
        //$objActSheet = $objPHPExcel->getActiveSheet();
        $i = 2;
        foreach ($insUserList as $item) {

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $item['code']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, $item['name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $item['phone']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $item['integral']);

            if ($item['is_enabled']) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, '是');
            } else {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, '否');
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $i, $item['institution_name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $i, $item['department_name']);
            //$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $i,User::getDepartmentByUserId($item['id']));
            $i++;

        }
        // 给当前活动的表设置名称
        //$objActSheet->setTitle('Simple2222');
        if (\Yii::$app->params['iswindows']) {
            //windows下使用该
            $filename = self::$download . '\userlist' . time() . '.xlsx';
        } else {
            //Linux下使用
            $filename = self::$download . '//' . 'userlist' . time() . '.xlsx';
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($filename);

        return $this->renderJson($filename, 0, 0);
    }

    /**
     * 根据user_id获取当前用户所在的部门
     */
    public function actionUserDepartmentsPartView()
    {
        $request = \Yii::$app->request;
        $user_id = $request->post('user_id');

        $manager = Manager::getCurrentManager();
    }

    /**
     * 会员详情概要
     */
    public function actionUserSummaryPartview()
    {
        $request = \Yii::$app->request;
        $user_id = $request->post('user_id');
        $user_summary = User::getUserDetail($user_id);
        //$user_integral=null;

        return $this->renderPartial('user-summary-partview', ['user_summary' => $user_summary]);

    }

    public function actionUserIntegralPartview()
    {
        $request = \Yii::$app->request;
        $user_id = $request->post('user_id');
        $page = $request->post("page");
        $start = $page;

        $startTime = $request->post("startTime");
        $endTime = $request->post("endTime");
        if ($start == '') {
            $start = 0;
            $page = 1;
        } else {
            $start = ($start - 1) * self::$pageSize;
        }
        if ($startTime == '') {
            $startTime = '0';
        }
        if ($endTime == '') {
            $endTime = '0';
        }

        $record = User::getUserIntegralRecord($start, self::$pageSize, $startTime, $endTime, $user_id);
        $total = User::getUserIntegralRecord($start, '-1', $startTime, $endTime, $user_id);

        $paginationDetail['page'] = $page;
        $paginationDetail['totalPage'] = ceil($total['totalnum'] / self::$pageSize);

        return $this->renderPartial('user-integral-partview',
            ['record' => $record,
                'paginationDetail' => $paginationDetail]);
    }
}